<template>
  <div class="chat-container">
    <!-- 左侧用户列表 --> 
    <div class="user-list">
   
      <h3 class="user-list-title">在线用户</h3>
      <div
        v-for="user in userList"
        :key="user.userId"
        class="user-item"
        :class="{ active: receiver === user.userId }"
        @click="selectUser(user)"
      >
        {{ user.nickName }}
      </div>
    </div>

    <!-- 右侧聊天区域 -->
    <div class="chat-right">
      <div class="chat-box" ref="chatBox">
        <div v-for="(message, index) in messages" :key="index" class="message">
          <div v-if="message.send == userId" class="self-message">
            <strong>{{ message.nickName }}:</strong> {{ message.message }}
          </div>
          <div v-else class="other-message">
            <strong>{{ message.nickName }}:</strong> {{ message.message }}
          </div>
        </div>
        <el-empty description="暂无记录" v-if="messages.length<1"/>
      </div>
      <div class="input-area">
        <input
          class="input"
          v-model="message"
          placeholder="消息内容"
          @keyup.enter="sendMessage"
        />
        <button class="button" @click="sendMessage">
          <svg
            xmlns="http://www.w3.org/2000/svg"
            fill="none"
            viewBox="0 0 24 24"
            stroke-width="1.5"
            stroke="currentColor"
            class="w-6 h-6"
          >
            <path
              stroke-linecap="round"
              stroke-linejoin="round"
              d="M4.5 12h15m0 0l-6.75-6.75M19.5 12l-6.75 6.75"
            />
          </svg>
          <div class="text">发送</div>
        </button>
      </div>
    </div>
  </div>
</template>

<script>
import { onMounted } from "vue";
import { getUsers,getMessages } from "@/api/user";

export default {
  data() {
    return {
      socket: null,
      messages: [],
      receiver: "",
      message: "",
      userId: "",
      nickName:"",
      onNickName:"",
      userList: [], // 存储用户列表
    };
  },
  methods: {
    initWebSocket() {
      this.socket = new WebSocket(
        `ws://113.44.189.152:9088/ws/chat?userId=${this.userId}`
      );
      this.socket.onmessage = this.handleMessage;
      this.socket.onopen = () => {
        console.log("WebSocket connected");
      };
      this.socket.onclose = () => {
        console.log("WebSocket disconnected");
      };
    },
    handleMessage(event) {
      console.log("Received message:", event);
      const messagestr = event.data;
      const message = JSON.parse(messagestr);
      message.nickName = message.nickName;
      this.messages.push(message);
      this.$nextTick(() => {
        this.$refs.chatBox.scrollTop = this.$refs.chatBox.scrollHeight;
      });
    },
    sendMessage() {
      if (this.receiver && this.message) {
        const message = {
          send: this.userId,
          receiver: this.receiver,
          message: this.message,
          nickName: this.nickName,
          onNickName:this.onNickName,
          id: Date.now(),  // 生成唯一ID
        };
        this.messages.push(message);
        this.socket.send(JSON.stringify(message));
        this.message = "";
        this.scrollToBottom();
      }
    }, scrollToBottom() {
      // Vue2中使用this.$nextTick确保DOM更新
      this.$nextTick(() => {
        // 通过this.$refs获取DOM元素
        const container = this.$refs.chatBox;
        if (container) {
          // 直接滚动到底部（无动画）
          //container.scrollTop = container.scrollHeight;

          // 如需平滑滚动（现代浏览器支持）：
           container.scrollTo({
             top: container.scrollHeight,
             behavior: 'smooth'  // 平滑滚动动画
           });
        }
      });
    },
    // 新增方法：获取用户列表
    async fetchUsers() {
      try {
        const res = await getUsers({ userId: this.userId });
        this.userList = res.data || [];
      } catch (error) {
        console.error("获取用户列表失败:", error);
      }
    },
    async fetchMessages(){
            try {
        const res = await getMessages({ userId: this.userId ,onUserId:this.receiver});
        this.messages = res.data || [];
        this.scrollToBottom();
      } catch (error) {
        console.error("获取历史消息失败:", error);
      }
    },
    // 新增方法：选择用户
    selectUser(user) {
      this.receiver = user.userId;
      this.onNickName = user.nickName;
      this.messages = [];
      this.fetchMessages();
    },
  },
  
  mounted() {
    let isUser = localStorage.getItem("user");
    if (isUser) {
      const user = JSON.parse(isUser);
      this.userId = user.userId;
      this.nickName =user.nickName;
      this.initWebSocket();
      this.fetchUsers();
    }
  },
  beforeDestroy() {
    if (this.socket) {
      this.socket.close();
    }
  },
};
</script>

<style scoped>
.chat-container {
  display: flex;
  height: 100%;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  min-height: 100vh;
  padding: 20px;
  box-sizing: border-box;
}

.user-list {
  width: 200px;
  border-right: 1px solid #ccc;
  overflow-y: auto;
  padding: 10px;
  background: rgba(255, 255, 255, 0.2);
  border-radius: 15px;
  box-shadow: 0 8px 32px rgba(0, 0, 0, 0.1);
  backdrop-filter: blur(10px);
  margin-right: 20px;
}

.user-list-title {
  margin: 0 0 15px 0;
  padding-bottom: 10px;
  border-bottom: 1px solid #ddd;
  color: #333;
  text-align: center;
  font-weight: 500;
}

.user-item {
  padding: 12px 15px;
  margin-bottom: 8px;
  border-radius: 10px;
  cursor: pointer;
  background: rgba(255, 255, 255, 0.3);
  color: #333;
  transition: all 0.3s ease;
  box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
}

.user-item:hover {
  background: rgba(255, 255, 255, 0.5);
  transform: translateY(-2px);
  box-shadow: 0 6px 12px rgba(0, 0, 0, 0.15);
}

.user-item.active {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: white;
  box-shadow: 0 6px 12px rgba(0, 0, 0, 0.2);
}

.chat-right {
  flex: 1;
  display: flex;
  flex-direction: column;
}

.chat-box {
  flex: 1;
  overflow-y: auto;
  padding: 20px;
  background: rgba(255, 255, 255, 0.2);
  border-radius: 15px;
  box-shadow: 0 8px 32px rgba(0, 0, 0, 0.1);
  backdrop-filter: blur(10px);
  margin-bottom: 20px;
}

.input-area {
  display: flex;
  justify-content: flex-end; /* 修改：将输入框整体靠右 */
  padding: 20px;
  background: rgba(255, 255, 255, 0.2);
  border-radius: 15px;
  box-shadow: 0 8px 32px rgba(0, 0, 0, 0.1);
  backdrop-filter: blur(10px);
}

input {
  flex: 1;
  margin-right: 10px;
  padding: 12px 15px;
  border: none;
  border-radius: 25px;
  outline: none;
  background: rgba(255, 255, 255, 0.3);
  color: #333;
  font-size: 16px;
  box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
  transition: all 0.3s ease;
}

.input {
  border: 2px solid transparent;
  /* width: 15em; */
  padding-left: 0.8em;
  outline: none;
  overflow: hidden;
  background-color: rgba(255, 255, 255, 0.3);
  border-radius: 25px;
  transition: all 0.5s;
  color: #333;
  font-size: 16px;
  box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
}

.input:focus,
input:hover {
  border: 2px solid #667eea;
  box-shadow: 0px 0px 0px 7px rgba(102, 126, 234, 0.2);
  background-color: rgba(255, 255, 255, 0.5);
}

button {
  padding: 12px 20px;
  border: none;
  border-radius: 25px;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: white;
  font-size: 16px;
  cursor: pointer;
  transition: all 0.3s ease;
  box-shadow: 0 4px 15px rgba(0, 0, 0, 0.2);
}

.button {
  background-color: transparent;
  color: #fff;
  border: none;
  border-radius: 25px;
  text-align: center;
  transition: all 0.6s ease;
  width: 100px;
  padding: 12px 0;
  display: flex;
  align-items: center;
  justify-content: center;
  position: relative;
  overflow: hidden;
}

.button:hover {
  background-color: rgba(255, 255, 255, 0.2);
  transform: translateY(-2px);
  box-shadow: 0 6px 20px rgba(0, 0, 0, 0.25);
}

.button svg {
  width: 1.6em;
  margin: -0.1em 0.1em 0.1em;
  position: absolute;
  display: flex;
  transition: all 0.6s ease;
  left: 10px;
}

.button:hover svg {
  transform: translateX(5px);
}

.button .text {
  margin-left: 25px;
}

.text {
  margin: 0 0.5em;
}

.form {
  transition: transform 0.5s linear;
}

.form:hover {
  transform: scaleY(1.1) scaleX(1.1);
}

.form2 {
  border-radius: 6px;
  border: 2px solid #ffffff00;
  transition: transform 0.3s ease, box-shadow 0.2s ease-out;
}

.form2:hover {
  transform: scaleY(1.05) scaleX(1.05);
  box-shadow: -2px 3px 3px 2px rgba(73, 78, 82, 0.5);
}

.form2:active {
  box-shadow: 0px 0px 0px 0px rgba(73, 78, 82, 0.2);
}

.message {
  margin-bottom: 10px;
}

.self-message {
  text-align: left;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: white;
  padding: 12px 16px;
  border-radius: 20px;
  max-width: 70%;
  align-self: flex-end; /* 确保消息气泡靠右对齐 */
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
}

.other-message {
  text-align: left;
  background: rgba(255, 255, 255, 0.3);
  color: #333;
  padding: 12px 16px;
  border-radius: 20px;
  max-width: 70%;
  align-self: flex-start; /* 对方消息靠左对齐 */
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
}

</style>